// https://leetcode.cn/problems/number-of-islands/

// 题干：给你一个由 '1'（陆地）和 '0'（水）组成的的二维网格，请你计算网格中岛屿的数量。
//       岛屿总是被水包围，并且每座岛屿只能由水平方向和/或竖直方向上相邻的陆地连接形成。
//       此外，你可以假设该网格的四条边均被水包围。

// 示例：输入：grid = [
//      ["1","1","1","1","0"],
//      ["1","1","0","1","0"],
//      ["1","1","0","0","0"],
//      ["0","0","0","0","0"]
//    ]
//      输出：1

// 碎语：floodFill算法，记得做标记，注意避免反向行走

#include <bits/stdc++.h>
using namespace std;

class Solution
{
    bool vis[301][301];
    int m, n, ret;
public:
    int numIslands(vector<vector<char>>& grid)
    {
        m = grid.size(), n = grid[0].size(), ret = 0;
        memset(vis, 0, sizeof(vis));

        for (int i = 0 ; i < m ; i++){
            for (int j = 0 ; j < n ; j++){
                if (!vis[i][j] && grid[i][j] == '1'){
                    vis[i][j] = true;
                    dfs(grid, i, j);
                    ret++;
                }
            }
        }

        return ret;
    }

    int dx[4] = {-1,1,0,0};
    int dy[4] = {0,0,-1,1};

    void dfs(vector<vector<char>>& grid, int i, int j)
    {
        for (int k = 0 ; k < 4 ; k++){
            int x = i + dx[k], y = j + dy[k];

            if (x >= 0 && x < m && y >= 0 && y < n && !vis[x][y] && grid[x][y] == '1'){
                vis[x][y] = true;

                dfs(grid, x, y);
            }
        }
    }
};

int main()
{
    Solution sol;
    vector<vector<char>> grid = {
            {'1','1','1','1','0'},
            {'1','1','0','1','0'},
            {'1','1','0','0','0'},
            {'0','0','0','0','0'}
    };

    cout << sol.numIslands(grid) << endl;

    return 0;
}
// 示例：输入：grid = [
//      ["1","1","1","1","0"],
//      ["1","1","0","1","0"],
//      ["1","1","0","0","0"],
//      ["0","0","0","0","0"]
//    ]